from channels.layers import get_channel_layer
import json


class SendJson(object):
    flag = False
    errorCode = 0
    errorMsg = '操作成功'
    data = {}

    def __init__(self, flag=True, error_code=0, error_msg='操作成功', **kwargs):
        self.flag = flag
        self.errorCode = error_code
        self.errorMsg = error_msg
        if kwargs:
            self.data = kwargs

    def to_dict(self):
        ret = {}
        ret.update(self.__dict__)
        if self.data:
            ret.update(self.data)
        return json.dumps(ret, ensure_ascii=False)


class Group(object):
    def __init__(self):
        self.group = []
        # self.channel_layer = get_channel_layer
        self.tag = ''

    async def add(self, tag, user, sp):
        i = 0
        flag = False
        item = {'user': user, 'sp': sp}
        print(dir(sp))
        if not self.group:
            # self.channel_layer = channel_layer
            # self.group.setdefault('channel_layer', default=channel_layer)
            self.group.append(item)
            self.tag = tag
            return
        else:
            for g in self.group:
                i += 1
                if user.pk == g['user'].pk:
                    # await g['sp'].close()
                    self.group[i - 1] = item
                    flag = True
                    break
            if not flag:
                self.group.append(item)

    async def delete(self, sp):
        i = 0
        flag = False
        if not self.group:
            return
        for g in self.group:
            i += 1
            if sp == g['sp']:
                flag = True
                break

        if flag:
            del self.group[i - 1]

    async def send_all_user(self, text_data=None):
        text = text_data
        is_json = self.is_json(text)

        if is_json:
            text = await self.encode_json(text)

        for g in self.group:
            await g['sp'].send(text_data=text)

    async def send_user(self, text_data=None, user=None):
        text = text_data
        is_json = self.is_json(text)
        if is_json:
            text = await self.encode_json(text)

        if user:
            for g in self.group:
                if user.pk == g['user'].pk:
                    await g['sp'].send(text_data=text)
                    break

    @classmethod
    async def decode_json(cls, text_data):
        return json.loads(text_data)

    @classmethod
    async def encode_json(cls, content):
        return json.dumps(content, ensure_ascii=False)

    @classmethod
    async def is_json(cls, text_data):
        if not '{' in text_data or not '}' in text_data:
            return False
        try:
            t = json.loads(text_data)
        except Exception:
            return False
        return True


group = Group()
